//
//  UIButton+MSRepeatedClick.m
//  PeopleForTheFirstMall
//
//  Created by mls on 2020/8/6.
//  Copyright © 2020 MS. All rights reserved.
//

#import "UIButton+MSRepeatedClick.h"
#import <objc/runtime.h>

@interface UIButton ()

@property (nonatomic, assign) NSTimeInterval kLastTime;

@end

@implementation UIButton (MSRepeatedClick)

- (void)ms_sendAction:(SEL)action
                   to:(id)target
             forEvent:(UIEvent*)event
{
    if(self.ms_timeInterval <= 0)
    {
        //此处methodA和methodB方法imp互换了，实际上执行sendAction；所以不会死循环
        [self ms_sendAction:action to:target forEvent:event];
        return;
    }
    
    BOOL b = (NSDate.date.timeIntervalSince1970 - self.kLastTime) >= self.ms_timeInterval;
    if (self.ms_timeInterval > 0)
    {
        //保存上次点击时间
        self.kLastTime = NSDate.date.timeIntervalSince1970;
    }
    
    if (b)
    {
        //此处methodA和methodB方法imp互换了，实际上执行sendAction；所以不会死循环
        [self ms_sendAction:action to:target forEvent:event];
    }
}

- (NSTimeInterval)kLastTime
{
    return [objc_getAssociatedObject(self, @selector(kLastTime)) doubleValue];
}

- (void)setKLastTime:(NSTimeInterval)kLastTime
{
    objc_setAssociatedObject(self, @selector(kLastTime), @(kLastTime), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSTimeInterval)ms_timeInterval
{
    return [objc_getAssociatedObject(self, _cmd) doubleValue];
}

- (void)setMs_timeInterval:(NSTimeInterval)ms_timeInterval
{
    objc_setAssociatedObject(self, @selector(ms_timeInterval), @(ms_timeInterval), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        SEL systemSEL = @selector(sendAction:to:forEvent:);
        SEL customSEL = @selector(ms_sendAction:to:forEvent:);
        Method systemMethod = class_getInstanceMethod(self, systemSEL);
        Method customSystemMethod = class_getInstanceMethod(self, customSEL);
        //将methodB的实现添加到系统方法中也就是说将methodA方法指针添加成方法methodB的返回值表示是否添加成功
        BOOL isAdd = class_addMethod(self, systemSEL, method_getImplementation(customSystemMethod), method_getTypeEncoding(customSystemMethod));
        //添加成功了说明本类中不存在methodB所以此时必须将方法b的实现指针换成方法A的，否则b方法将没有实现。
        if(isAdd)
        {
            class_replaceMethod(self, customSEL, method_getImplementation(systemMethod), method_getTypeEncoding(systemMethod));
        }
        else
        {
            //添加失败了说明本类中有methodB的实现，此时只需要将methodA和methodB的IMP互换一下即可。
            method_exchangeImplementations(systemMethod, customSystemMethod);
        }
    });
}


@end
